/***************************************************************************
 *   Copyright (C) 2007 by crackedmind                                     *
 *   digital.stream.of.mind@gmail.com                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "precompiled.hpp"
#include "SharedLibrary.hpp"
#include <dlfcn.h>

SharedLibrary::~SharedLibrary()
{
    //if ( _error != NULL )
    //    LocalFree((void*)_error);

    if ( this->autoUnload() == true )
        this->unload();
}

bool SharedLibrary::load( SL_Flags flags /* = SL_DEFAULT */ )
{
    _handle = dlopen(_libname, RTLD_LAZY);

    if ( _libname != NULL )
        strlcpy(_name, _libname, PATH_MAX);

    if ( _handle != NULL )  {
     //   ::GetModuleFileName(_handle, _path, MAX_PATH);
        _isLoaded = true;

        return true;
    }

    return false;
}

bool SharedLibrary::unload ()
{
    if ( this->isLoaded() ) {
        bool res = dlclose(_handle);

        if ( res != 0 )
            return true;
    }

    return false;
}

const char * SharedLibrary::error()
{
    //DWORD err = ::GetLastError();

    //::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
     //   (LPTSTR) &_error, 0, NULL );

    return _error;
}

void * SharedLibrary::symbol ( const char* proc )
{
    return (void*)dlsym(_handle, proc);
}
